//
//  MainViewController.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/20/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "MainViewController.h"
#import "DetailsViewController.h"
#import "XDTools.h"
#import "SupervisionListCell.h"
#import "XDSearchBar.h"
#import "SaomiaoViewController.h"
#import "InitDataRequset.h"
#import "Request.h"
#import "FMDatabase.h"
#import "PropertyItem.h"
#import "CurrentTimeItem.h"

#define cell_tag 101

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.initlalizeBtn.hidden =NO;
    self.initlalizeLabel.hidden =NO;
    //[self calculateRemindBtnFrame:[XDTools sharedXDTools].waitCumitCount];
    [self calculateRemindBtnFrame:[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"]];
    
    if([XDTools sharedXDTools].isupClick){
        [self getDatas:NO];
    }
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
//    searchView.searchBar.text = nil;
    [searchView.searchBar resignFirstResponder];

}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.

    [XDTools sharedXDTools].mvc = self;
    
    chooseIndex = 1;
    self.dataArray = [[NSMutableArray alloc] init];
    self.noStickArray = [[NSMutableArray alloc] init];
    self.hadStickArray = [[NSMutableArray alloc] init];
    self.searchArray = [[NSMutableArray alloc] init];
    isSearch = NO;
    self.mDictionary = [[NSMutableDictionary alloc] init];
    
    self.titleLabel.text =[NSString stringWithFormat:@"%@-设备监造",[UserInfo sharedUserInfo].project_code];
    
    [self setHiddenBackBtn:YES];
    [self initsegmentedView];   //创建段落选择器
    [self initsearchView];      //创建搜索
    [self initListHeader];     //创建表头
    [self initList];            //创建列表
    initRequset = [[InitDataRequset alloc] init];
    initRequset.delegate =self;
    initRequset.tag = 12345;
    
//    if([[NSUserDefaults standardUserDefaults] boolForKey:@"isFirstStart"]||[[NSUserDefaults standardUserDefaults] boolForKey:@"isChangeuuid"]){
//        [self getDatas:NO];
//    }else{
//        [self initHomePageDatas:nil];
//    }
    
    
    waitingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, mUI_Screen_Width,mUI_Screen_Height)];
    waitingView.backgroundColor = [UIColor blackColor];
    waitingView.alpha = 0.6;
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:CGRectMake(620/2.0f,870/2.0f, mHomePage_Download_Img.size.width, mHomePage_Download_Img.size.height)];
    imageView.image = mHomePage_Download_Img;
    [waitingView addSubview:imageView];
    [[UIApplication sharedApplication].keyWindow addSubview:waitingView];
    waitingView.hidden =YES;

    int a = [[[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"] intValue];
    if (a>0&&![[NSUserDefaults standardUserDefaults] boolForKey:@"isChangeuuid"]){
        [self initHomePageDatas:nil];
        [self gotoSubmitViewController];
    }else{
        if([[NSUserDefaults standardUserDefaults] boolForKey:@"isChangeuuid"]){
            FMDatabase * db = [XDTools getDb];
            if(![db open]){
                return;
            }
            BOOL aa1 = [db executeUpdate:@"DELETE FROM T_TRACE_SUMIT"];
            if(!aa1){
                [db close];
                return;
            }
            [db close];
        }
        [self getDatas:NO];
    }
}

#pragma mark ======================UI create ======================
-(void)initsegmentedView
{   //创建段落选择器
    segmentedView = [[XDSegmentedView alloc] initWithFrame:CGRectMake(20, 17, mHomePage_Segmented_Left_Normal_Img.size.width+mHomePage_Segmented_Middle_Normal_Img.size.width+mHomePage_Segmented_Right_Normal_Img.size.width, mHomePage_Segmented_Right_Normal_Img.size.height)];
    segmentedView.delegate = self;
    [self.contentView addSubview:segmentedView];
    
    [segmentedView.leftButton setTitle:@"未贴" forState:UIControlStateNormal];
    [segmentedView.middleButton setTitle:@"全部" forState:UIControlStateNormal];
    [segmentedView.rightButton setTitle:@"已贴" forState:UIControlStateNormal];
}

-(void)initsearchView
{
    //创建搜索610x56  578 32
    searchView = [[XDSearchBar alloc] initWithFrame:CGRectMake(width_x(segmentedView)+744/2.0f-8, 34/2.0f, 610/2.0f+16, 56/2.0f)];
    searchView.searchBar.placeholder = @"名称、型号或厂家";
    searchView.searchBar.delegate = self;
    searchView.backgroundColor = [UIColor clearColor];
    [self.contentView addSubview:searchView];
    
}

-(void)initListHeader
{
    //创建表头
    headerTabelView = [[UITableView alloc] initWithFrame:CGRectMake(18, height_y(segmentedView)+20,self.contentView.frame.size.width-36, mHomepage_head_Height) style:UITableViewStylePlain];
    headerTabelView.delegate = self;
    headerTabelView.dataSource = self;
    headerTabelView.userInteractionEnabled = NO;
    headerTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:headerTabelView];
    
}

-(void)initList
{
    //创建列表
    self.homePageTableview = [[UITableView alloc] initWithFrame:CGRectMake(headerTabelView.frame.origin.x,height_y(headerTabelView),headerTabelView.frame.size.width,self.contentView.frame.size.height-(height_y(headerTabelView))) style:UITableViewStylePlain];
    _homePageTableview.delegate = self;
    _homePageTableview.dataSource = self;
    _homePageTableview.backgroundColor = [UIColor clearColor];
    _homePageTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.contentView addSubview:_homePageTableview];
    
    //创建下拉刷新
    UIRefreshControl * headerRefresh = [[UIRefreshControl alloc] init];
    headerRefresh.tintColor = [UIColor grayColor];
    headerRefresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"\n"];
   [headerRefresh addTarget:self action:@selector(doPullRefresh:) forControlEvents:UIControlEventValueChanged];
    [_homePageTableview addSubview:headerRefresh];

}
#pragma mark ================调接口请求数据=======================
-(void)getDatas:(BOOL)isAddRequset
{
    waitingView.hidden =NO;
    if (!isAddRequset){
        [XDTools sharedXDTools].isReflash =NO; //这个是数据库操作时判断全部下载还是增量下载的标示
        [initRequset initInitDataRequsetDict];
        [initRequset getTagsInfomation:nil];
        [initRequset getPropertyInfomation:nil];
        [initRequset getPropertyWithLabelInfomation:nil];
        [initRequset getScanInfomation:nil];
        [initRequset getSupervisionInfomation:nil];
    }else{
        [XDTools sharedXDTools].isReflash =YES;
        [initRequset initInitDataRequsetDict];
        [initRequset getTagsInfomation:[[NSUserDefaults standardUserDefaults] valueForKey:mTagsCurrentTime]];
        [initRequset getPropertyInfomation:[[NSUserDefaults standardUserDefaults] valueForKey:mPropertyCurrentTime]];
        [initRequset getPropertyWithLabelInfomation:[[NSUserDefaults standardUserDefaults] valueForKey:mPropertyWithLabelCurrentTime]];
        [initRequset getScanInfomation:[[NSUserDefaults standardUserDefaults] valueForKey:mScanCurrentTime]];
        [initRequset getSupervisionInfomation:[[NSUserDefaults standardUserDefaults] valueForKey:mSupervisionCurrentTime]];
    }

}

#pragma mark ================这个是增量下载和全部下载时需要实现的代理方法===================
-(void)reloadDataFromDB:(InitDataRequset *)reRuequset
{
    [XDTools sharedXDTools].isupClick=NO;
     waitingView.hidden =YES;
    [self initHomePageDatas:reRuequset];
}

-(void)failInitRequest
{
    waitingView.hidden =YES;
    [XDTools showTips:@"获取数据失败" toView:[UIApplication sharedApplication].keyWindow];
    [self initHomePageDatas:nil];
}

#pragma mark =================取数据===========================
-(void)initHomePageDatas:(InitDataRequset *)reRuequset
{
    [_dataArray removeAllObjects];
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"数据打开失败");
        return;
    }
    FMResultSet * rs = [db executeQuery:@"SELECT * FROM T_TRACE_ASSERTS"];
    while ([rs next]) {
        PropertyItem * item = [[PropertyItem alloc] init];
        [item setPropertyid:[rs objectForColumnName:@"id"]];
        [item setCode:[rs objectForColumnName:@"code"]];
        [item setName:[rs objectForColumnName:@"name"]];
        [item setModel:[rs objectForColumnName:@"model"]];
        [item setFactory_name:[rs objectForColumnName:@"factory_name"]];
        [item setSupervision_linkman:[rs objectForColumnName:@"supervision_linkman"]];
        [_dataArray addObject:item];
    }
    [db close];
    
    for (int i = 0 ; i < [_dataArray count];i++){
        int tagCount=0;
        PropertyItem * item = [_dataArray objectAtIndex:i];
        FMDatabase * db2 = [XDTools getDb];
        if (![db2 open]){
            DDLOG(@"首页-->标签数量-->数据库打开失败");
            return;
        }
        FMResultSet * rs2 = [db2 executeQuery:@"SELECT * FROM T_TRACE_ASSERTS_TAG WHERE assert_id = ?",item.propertyid];
        while ([rs2 next]) {
            tagCount++;
        }
        item.tagCount = [NSString stringWithFormat:@"%d",tagCount];
        [db close];
    }
    
    [_noStickArray removeAllObjects];
    [_hadStickArray removeAllObjects];
    for (int i = 0 ; i <[_dataArray count];i++){
        PropertyItem * item = [_dataArray objectAtIndex:i];
        if ([item.tagCount intValue]==0){
            [_noStickArray addObject:item];
        }else{
            [_hadStickArray addObject:item];
        }
    }
    
    //未贴数组排序
    NSArray * aray = [_noStickArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        PropertyItem * item1 = obj1;
        PropertyItem * item2 = obj2;
        if ([item1.code compare: item2.code]==1) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([item1.code compare:item2.code]==-1) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    [_noStickArray removeAllObjects];
    [_noStickArray addObjectsFromArray:aray];
    
    //已贴数组排序
    for (int i = 0;i<[_hadStickArray count];i++){
        PropertyItem * item = [_hadStickArray objectAtIndex:i];
        NSString * last_time = @"0"; //贴标签时，最后一次贴标签的时间
        FMDatabase * db3 = [XDTools getDb];
        if (![db3 open]){
            DDLOG(@"首页-->已贴排序-->打开数据库失败");
            return;
        }
        FMResultSet * rs3 = [db3 executeQuery:@"SELECT * FROM T_TRACE_ASSERTS_TAG WHERE assert_id = ?",item.propertyid];
        while ([rs3 next]){
            NSString * create_time = [rs3 objectForColumnName:@"create_time"];
            if ([last_time compare:create_time] == NSOrderedAscending){
                last_time = [NSString stringWithFormat:@"%@",create_time];
            }
        }
        item.last_create_time = last_time;
        [db close];
    }
    NSArray * aray2 = [_hadStickArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        PropertyItem * item1 = obj1;
        PropertyItem * item2 = obj2;
        if ([item1.last_create_time compare:item2.last_create_time]==-1) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        if ([item1.last_create_time compare: item2.last_create_time ] ==1) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
    }];
    [_hadStickArray removeAllObjects];
    [_hadStickArray addObjectsFromArray:aray2];

    //全部排序
    [_dataArray removeAllObjects];
    [_dataArray addObjectsFromArray:aray];
    [_dataArray addObjectsFromArray:aray2];
    
    
    //判断“全部”中设备是否有图片(并给已贴重新赋值)
    [_hadStickArray removeAllObjects];
    for (int i =0;i<[_dataArray count];i++){
        PropertyItem * item = [_dataArray objectAtIndex:i];
        FMDatabase * db4 = [XDTools getDb];
        if (![db4 open]){
            DDLOG(@"首页-->是否有图片-->扫描记录表-->打开失败");
        }
        
        FMResultSet * rs4 = [db4 executeQuery:@"SELECT * FROM T_TRACE_SCAN_LOG WHERE assert_id = ?",item.propertyid];
        while ([rs4 next]) {
            if(IS_NOT_EMPTY([rs4 objectForColumnName:@"breviaryphoto"])){
                item.havePhoto =YES;
            }
        }
        [db close];
        
        if ([item.tagCount intValue]>0){
            [_hadStickArray addObject:item];
        }
    }
    
    //未贴中的设备都没有图片
    for (int i =0;i<[_noStickArray count];i++){
        PropertyItem * item = [_noStickArray objectAtIndex:i];
        item.havePhoto =NO;
    }
    

    [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateNormal];
    [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateDisabled];
    [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateNormal];
    [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateDisabled];
    [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateNormal];
    [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateDisabled];
    
    [_homePageTableview reloadData];

}

#pragma mark ============系统的刷新==========================
-(void)doPullRefresh:(UIRefreshControl *)refresh
{
    NSString * str = [[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"];
    if(![XDTools NetworkReachable]){
        [refresh endRefreshing];
        [XDTools showTips:@"未连接到网络" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    if (IS_NOT_EMPTY(str)){
        [refresh endRefreshing];
        [XDTools showTips:@"有未提交数据，无法下载" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm"];//@"MMM d, h:mm a"];
    NSString *lastUpdated = [[NSUserDefaults standardUserDefaults] valueForKey:@"lastDate"];
    if(IS_NOT_EMPTY(lastUpdated)){
        refresh.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
    }
    [[NSUserDefaults standardUserDefaults] setValue:[NSString stringWithFormat:@"上次更新日期 %@",
                                                     [formatter stringFromDate:[NSDate date]]] forKey:@"lastDate"];
    [self getDatas:YES];
    
    [self performSelector:@selector(endend:) withObject:refresh afterDelay:1];
}
-(void)endend:(UIRefreshControl *)refresh
{
    refresh.attributedTitle = [[NSAttributedString alloc] initWithString:@"\n"];
    [refresh endRefreshing];
    [_homePageTableview reloadData];
}

#pragma mark ======================XDsegmentedView Delegate========
-(void)changeSengmentIndex:(int)index
{
    chooseIndex =index;
    isSearch =NO;
    
    [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateNormal];
    [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateNormal];
    [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateNormal];
    [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateDisabled];
    [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateDisabled];
    [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateDisabled];
    
    [_homePageTableview reloadData];
    [searchView.searchBar resignFirstResponder];
    searchView.searchBar.text = nil;
    DDLOG_CURRENT_METHOD;
}

#pragma mark =====================UISearchBar Delegate=============
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
  
}

-(BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar
{
    return YES;
}

-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
 
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    DDLOG(@"searchBar.text = %@",searchBar.text);
    NSString * searchString = searchBar.text;
    NSMutableArray * array;
    if (chooseIndex == 0){
        array = _noStickArray;
    }else if (chooseIndex == 1){
        array = _dataArray;
    }else{
        array = _hadStickArray;
    }
    
    if (!IS_NOT_EMPTY(searchBar.text)){
        isSearch =NO;
        [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateNormal];
        [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateNormal];
        [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateNormal];
        [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_noStickArray.count] forState:UIControlStateDisabled];
        [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_dataArray.count] forState:UIControlStateDisabled];
        [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_hadStickArray.count] forState:UIControlStateDisabled];
        [_homePageTableview reloadData];
        return;
    }

    [_searchArray removeAllObjects];
    for (int i =0;i<array.count;i++){
        PropertyItem * item = [array objectAtIndex:i];
        NSRange range1 = [item.name rangeOfString:searchString];
        NSRange range2 = [item.model rangeOfString:searchString];
        NSRange range3 = [item.factory_name rangeOfString:searchString];
        if ((range1.location!=NSNotFound)||(range2.location!=NSNotFound)||(range3.location !=NSNotFound)){
            [_searchArray addObject:item];
        }
    }
    
    if (chooseIndex == 0){
        [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_searchArray.count] forState:UIControlStateNormal];
        [segmentedView.leftButton setTitle:[NSString stringWithFormat:@"未贴(%d)",_searchArray.count] forState:UIControlStateDisabled];
    }else if (chooseIndex == 1){
        [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_searchArray.count] forState:UIControlStateNormal];
        [segmentedView.middleButton setTitle:[NSString stringWithFormat:@"全部(%d)",_searchArray.count] forState:UIControlStateDisabled];
    }else{
        [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_searchArray.count] forState:UIControlStateNormal];
        [segmentedView.rightButton setTitle:[NSString stringWithFormat:@"已贴(%d)",_searchArray.count] forState:UIControlStateDisabled];
    }
    
    isSearch =YES;
    [_homePageTableview reloadData];
}

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchView.searchBar resignFirstResponder];
    DDLOG_CURRENT_METHOD;
}

#pragma mark ======================UITableView Delegate============
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == headerTabelView){
        return mHomepage_head_Height;
    }else{
        return mHomepage_Cell_Height;
    }
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == headerTabelView){
        return 1;
    }else{
        if (isSearch){
            return [_searchArray count];
        }else{
            if (chooseIndex ==0){
                return [_noStickArray count];
            }else if (chooseIndex == 1){
                return [_dataArray count];
            }else{
                return [_hadStickArray count];
            }
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == headerTabelView){
        static NSString * cellName = @"cell";
        SupervisionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        }
        cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Head_bg_Img];
        [cell isHarderTableViewCell];
        cell.photoImage.hidden =YES;
        cell.numberLabel.text = [self.assert_info_array objectAtIndex:0];
        cell.assertIdLabel.text = [self.assert_info_array objectAtIndex:1];
        cell.assertNameLabel.text = [self.assert_info_array objectAtIndex:2];
        cell.assertModelLabel.text = [self.assert_info_array objectAtIndex:3];
        cell.factoryNameLabel.text = [self.assert_info_array objectAtIndex:4];
        cell.tagsCountLabel.text = [self.assert_info_array objectAtIndex:5];
        UILabel * label = [UILabel initLabel:CGRectMake(width_x(cell.tagsCountLabel), 0,130/2.0f, mHomepage_head_Height) textFont:mHomepage_Head_text_Font textColor:mHomepage_Head_Text_Color textAlignment:NSTextAlignmentCenter];
        label.text = [self.assert_info_array objectAtIndex:6];
        [cell addSubview:label];
        
        return cell;   
    }else{
        static NSString * cellName = @"cell2";
        SupervisionListCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
        if (cell == nil){
            cell = [[SupervisionListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        }
        cell.photoImage.hidden =NO;
        PropertyItem * item;
        if (isSearch){
            if ([_searchArray count]==0){
                return cell;
            }
            item = [_searchArray objectAtIndex:indexPath.row];
        }else{
            if (chooseIndex == 0){
                if ([_noStickArray count]==0){
                    return cell;
                }
                item = [_noStickArray objectAtIndex:indexPath.row];
            }else if (chooseIndex == 1){
                if ([_dataArray count]==0){
                    return cell;
                }
                item = [_dataArray objectAtIndex:indexPath.row];
            }else{
                if ([_hadStickArray count]==0){
                    return cell;
                }
                item = [_hadStickArray objectAtIndex:indexPath.row];
            }
        }
        
        if (indexPath.row%2){
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Even_Img];
        }else{
            cell.diselectBg.image = [XDTools stretchableImag:mHomepage_Cell_Odd_Img];
        }

        cell.numberLabel.text = [NSString stringWithFormat:@"    %d",indexPath.row+1];
       
        
        if (item.havePhoto){
            cell.photoImage.hidden=NO;
        }else{
            cell.photoImage.hidden =YES;
        }
        cell.assertIdLabel.text = item.code;
        cell.assertNameLabel.text =item.name;
        cell.assertModelLabel.text = item.model;
        cell.factoryNameLabel.text = item.factory_name;
        cell.tagsCountLabel.text = item.tagCount;
        
        CGRect idRect = [XDTools xyAutoSizeOfWidget:cell.assertIdLabel andSize:CGSizeMake(361/2.0f, mHomepage_Cell_Height) andtextFont:15];
        CGRect nameRect = [XDTools xyAutoSizeOfWidget:cell.assertNameLabel andSize:CGSizeMake(425/2.0f, mHomepage_Cell_Height) andtextFont:15];
        CGRect modelRect = [XDTools xyAutoSizeOfWidget:cell.assertModelLabel andSize:CGSizeMake(361/2.0f, mHomepage_Cell_Height) andtextFont:15];
        CGRect factoryRect = [XDTools xyAutoSizeOfWidget:cell.factoryNameLabel andSize:CGSizeMake(425/2.0f, mHomepage_Cell_Height) andtextFont:15];
        
        cell.assertIdLabel.frame = CGRectMake(idRect.origin.x, idRect.origin.y,361/2.0f, mHomepage_Cell_Height);
        cell.assertNameLabel.frame = CGRectMake(nameRect.origin.x, nameRect.origin.y, 425/2.0f, mHomepage_Cell_Height);
        cell.assertModelLabel.frame = CGRectMake(modelRect.origin.x, modelRect.origin.y, 361/2.0f, mHomepage_Cell_Height);
        cell.factoryNameLabel.frame = CGRectMake(factoryRect.origin.x, factoryRect.origin.y, 425/2.f, mHomepage_Cell_Height);
        
        [cell.stickBtn addTarget:self action:@selector(labelling:) forControlEvents:UIControlEventTouchUpInside];
        cell.stickBtn.tag = cell_tag+indexPath.row;
        return cell;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PropertyItem * item;
    if (isSearch){
        item = [_searchArray objectAtIndex:indexPath.row];
    }else{
        if (chooseIndex == 0){
            item = [_noStickArray objectAtIndex:indexPath.row];
        }else if (chooseIndex ==1){
            item = [_dataArray objectAtIndex:indexPath.row];
        }else{
            item = [_hadStickArray objectAtIndex:indexPath.row];
        }
    }
    
    [_mDictionary setValue:item.propertyid forKey:@"id"];
    [_mDictionary setValue:item.code forKey:@"code"];
    [_mDictionary setValue:item.name forKey:@"name"];
    [_mDictionary setValue:item.supervision_linkman forKey:@"supervision_linkman"];

    DetailsViewController * dvc = [[DetailsViewController alloc] init];
    dvc.assert_id = item.propertyid;
    
    [self.navigationController pushViewController:dvc animated:YES];
}

#pragma mark =========================UIButton click===========================
-(void)labelling:(UIButton *)sender
{
    NSMutableArray * array;
    if (isSearch){
        array = _searchArray;
    }else{
        if (chooseIndex == 0){
            array = _noStickArray;
        }else if(chooseIndex == 1){
            array = _dataArray;
        }else{
            array = _hadStickArray;
        }
    }
    PropertyItem * item = [array objectAtIndex:sender.tag-cell_tag];
    
    [_mDictionary setValue:item.propertyid forKey:@"id"];
    [_mDictionary setValue:item.code forKey:@"code"];
    [_mDictionary setValue:item.name forKey:@"name"];
    [_mDictionary setValue:item.supervision_linkman forKey:@"supervision_linkman"];
    
    SaomiaoViewController * saomiaoVC = [[SaomiaoViewController alloc] init];
    [self.navigationController pushViewController:saomiaoVC animated:YES];
    DDLOG_CURRENT_METHOD;
}

#pragma mark ========================重写数据初始化 点击事件========================
-(void)initlalizeData
{
    DDLOG_CURRENT_METHOD;
    NSString * str = [[NSUserDefaults standardUserDefaults] valueForKey:@"waitCunitCount"];
    if(![XDTools NetworkReachable]){
        [XDTools showTips:@"未连接到网络" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    if (IS_NOT_EMPTY(str)){
        [XDTools showTips:@"有未提交数据，无法下载" toView:[UIApplication sharedApplication].keyWindow];
        return;
    }
    [self getDatas:NO];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
